package com.example.forum.services.impl;

import com.example.forum.dao.MessageMapper;
import com.example.forum.model.Message;
import com.example.forum.services.MessageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    MessageMapper messageMapper;

    /**
     * 创建一条私信(站内信)————Session、Message
     * @param message
     */
    @Override
    public void create(Message message) {
        //设置默认值
        message.setState((byte) 0); //表⽰未读状态
        message.setDeleteState((byte) 0);
        //设置创建与更新时间
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        messageMapper.insertSelective(message);
    }

    /**
     * 当前用户的私信未读数量————Session、用户id
     * @param userId
     * @return
     */
    @Override
    public Integer selectUnreadCount(Long userId) {
        return messageMapper.selectUnreadCount(userId);
    }

    /**
     * 查询私信列表————Session、接收者id(当前登录的用户就是接收者)
     * @param receiveUserId
     * @return
     */
    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        return messageMapper.selectByReceiveUserId(receiveUserId);
    }

    /**
     * 查询某条私信————Session、私信id
     * @param id
     * @return
     */
    @Override
    public Message selectById(Long id) {
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }

    /**
     * 更新某条私信的状态————Session、私信id、状态码(0未读、1已读、2已回复)
     * @param id
     * @param state
     */
    @Override
    public void updateStateById(Long id, Byte state) {
        Message message = new Message();
        message.setId(id);
        message.setState(state);
        messageMapper.updateByPrimaryKeySelective(message);
    }

    /**
     * 回复私信————Session、被回复的私信id、回复的内容
     * @param repliedId
     * @param message
     */
    @Override
    public void reply(Long repliedId, Message message) {
        Message messageReplied = messageMapper.selectByPrimaryKey(repliedId);
        message.setReceiveUserId(messageReplied.getPostUserId());
        //设置默认值
        message.setState((byte) 0); //表⽰未读状态
        message.setDeleteState((byte) 0);
        //设置创建与更新时间
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        updateStateById(repliedId, (byte) 2);//更新状态为已经回复！
        messageMapper.insertSelective(message);

    }

}
